# -*- coding: utf-8 -*-
from pyquery import PyQuery
from datetime import datetime
from zc_core.model.items import Catalog, Brand, Supplier, Sku, ItemData
from zc_core.pipelines.helper.supplier_helper import SupplierHelper
from zc_core.util.common import parse_number
from zc_core.util.encrypt_util import md5
from zc_core.util.sku_id_parser import convert_id2code
from baqc.matcher import *


# 解析catalog列表
def parse_catalog(response):
    jpy = PyQuery(response.text)
    div_list = jpy('div.product')

    cats = list()
    for idx, div in enumerate(div_list.items()):
        # 一级分类
        cat1_span = div('h3 span')
        cat1_id = 'nav{}'.format(str(idx))
        cat1_name = cat1_span.text().strip()
        cat1 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat1)

        # 二级分类
        cat2_divs = div.next()('div.cf dl.fore1')
        for cat2_div in cat2_divs.items():
            cat2_link = cat2_div('dt span a')
            cat2_id = match_cat_id(cat2_link.attr('href'))
            cat2_name = cat2_link.text().replace('>', '').strip()
            cat2 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat2)

            # 三级分类
            cat3_links = cat2_div('dd span a')
            for cat3_link in cat3_links.items():
                cat3_id = match_cat_id(cat3_link.attr('href'))
                cat3_name = cat3_link.text().strip()
                cat3 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(cat3)

    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 解析brand列表
def parse_brand(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    a_list = jpy('div.tabcon-multi a')
    brands = list()
    for br in a_list.items():
        brand = Brand()
        brand['id'] = match_brand_id(br.attr('href'))
        if br.attr('title'):
            brand['name'] = clean_brand_text(br.attr('title'))
        else:
            brand['name'] = clean_brand_text(br.text())
        brand['batchNo'] = meta.get('batchNo')
        brands.append(brand)

    return brands


# 解析brand列表
def parse_supplier(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    a_list = jpy('div.filtername:contains("电商：") + dl:eq(0) a')
    suppliers = list()
    for sp in a_list.items():
        supplier = Supplier()
        supplier['id'] = match_supplier_id(sp.attr('href'))
        supplier['name'] = clean_supplier_text(sp.attr('title'))
        supplier['batchNo'] = response.meta.get('batchNo')
        suppliers.append(supplier)

    return suppliers


# 解析sku列表页数
def parse_total_page(response):
    jpy = PyQuery(response.text)
    last_url = jpy('nav.pagination span.last a').attr('href')

    return match_sku_total_page(last_url)


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sp_helper = SupplierHelper()

    skus = list()
    jpy = PyQuery(response.text)
    sku_links = jpy('div.gp-list-view-search ul > a')
    for sku_link in sku_links.items():
        sku = Sku()
        link = sku_link.attr('href')
        sp_name = sku_link('font.textm').text()
        sale_price = sku_link('b.int').text()

        sku_id = match_sku_id_from_sku(link)
        sku['skuId'] = sku_id
        sku['batchNo'] = batch_no
        sku['supplierId'] = sp_helper.get_id_by_name(sp_name.strip())
        price = parse_number(sale_price)
        sku['salePrice'] = price
        sku['originPrice'] = price
        skus.append(sku)

    return skus


# 解析stock
def parse_stock(response):
    if response.text and 'true' in response.text:
        return True

    return False


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    jpy = PyQuery(response.text)
    result = ItemData()

    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    nav = jpy('div.breadmain a')
    sale_price = match_sale_price(response.text)
    origin_price = jpy('del#website_price_tag').text()
    total_sales = jpy('div.cumulativeamount').text()
    # 品 目 编 号
    gov_catalog_id = jpy('div.attribute div.dt:contains("品") + div.gs').eq(0).text()
    # 商 品 编 号
    supplier_sku_id = jpy('div.attribute div.dt:contains("商") + div.gs').eq(0).text()
    # 供  应  商
    supplier = jpy('div.attribute div.dt:contains("供") + div.gs').eq(0)
    brand = jpy('table.Ptable td:contains("品牌") + td').text()
    model_attrs = jpy('table.Ptable td:contains("型号")')
    images = jpy('div.spec-scroll div.items li img')

    # -------------------------------------------------
    # 批次编号
    result['batchNo'] = batch_no
    # 平台商品ID（用于业务系统）
    result['skuId'] = sku_id
    # 平台商品名称（标题）
    result['skuName'] = jpy('div.goodsdetail_left h1').eq(0).text().strip()
    # 平台商品主图（主图地址）
    if images:
        result['skuImg'] = images.eq(0).attr('src').strip()
    # 一级分类编号
    result['catalog1Id'] = ''
    # 一级分类名称
    result['catalog1Name'] = ''
    # 二级分类编号
    result['catalog2Id'] = ''
    # 二级分类名称
    result['catalog2Name'] = ''
    # 三级分类编号
    # 735 清洁用品  710 清洁用品
    catalog3_id = match_cat_id(nav.eq(1).attr('href'))
    # TODO 兼容错误数据
    if catalog3_id == '735':
        catalog3_id = '710'
    if catalog3_id == '804':
        catalog3_id = '817'
    result['catalog3Id'] = catalog3_id
    # 三级分类名称
    result['catalog3Name'] = nav.eq(1).text().strip()
    # 政府采购品目编码
    if gov_catalog_id and gov_catalog_id != '暂无':
        result['govCatId'] = gov_catalog_id.strip()
    # 实际销售价格
    result['salePrice'] = parse_number(sale_price)
    # 商品原价（商城原价、市场价格）
    result['originPrice'] = parse_number(origin_price)
    # 累积采购金额
    result['soldAmount'] = parse_number(total_sales)
    # 品牌
    if brand and brand.strip():
        result['brandName'] = brand.strip()
        result['brandId'] = md5(brand.strip())
    # 供应商
    sp_name = supplier('font.textm').text()
    if sp_name and sp_name.strip():
        result['supplierName'] = sp_name.strip()
        result['supplierId'] = md5(sp_name.strip())
    # 供应商商品编码
    sp_sku_id = supplier_sku_id.strip()
    result['supplierSkuId'] = sp_sku_id
    plat_code = None
    if sp_name == '得力':
        plat_code = 'deli'
    result['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)
    # 供应商商品链接
    if supplier:
        result['supplierSkuLink'] = supplier('a').attr('href').strip()
    # 品牌型号
    if model_attrs and len(model_attrs):
        for model_attr in model_attrs.items():
            if model_attr.text().strip() == '型号':
                model = model_attr.next('td').text().strip()
                if model:
                    result['brandModel'] = model[0:190]
    result['genTime'] = datetime.utcnow()
    # -------------------------------------------------

    return result
